package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.GZIPOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GZIPCompressesData {
	private static final int _BUFFER_SIZE = 1024;

	public static byte[] compress(byte[] dataSource) throws IOException {
		ByteArrayOutputStream baos = null;
		GZIPOutputStream gos = null;

		int bytesToWrite = 0;
		int currentPosition = 0;
		try {

			baos = new ByteArrayOutputStream(dataSource.length);
			gos = new GZIPOutputStream(baos);

			while (currentPosition < dataSource.length) {
				bytesToWrite = _BUFFER_SIZE;
				if (bytesToWrite > (dataSource.length - currentPosition)) {
					bytesToWrite = (dataSource.length - currentPosition);
				}

				gos.write(dataSource, currentPosition, bytesToWrite);
				currentPosition += bytesToWrite;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		} finally {
			try {
				if (gos != null) {
					gos.finish();
					gos.close();
				}
				if (baos != null) {
					baos.close();
				}
			} catch (Exception exception) {
			}
		}
		return baos.toByteArray();
	}

	public static void compress(InputStream inputStream,
	                            OutputStream outputStream) throws IOException {
		byte[] buffer = new byte[_BUFFER_SIZE];
		GZIPOutputStream gos = null;

		try {
			gos = new GZIPOutputStream(outputStream);

			int bytesRead = 0;
			while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
				gos.write(buffer, 0, bytesRead);
			}
		} catch (IOException exception) {
			throw exception;
		} finally {
			if (gos != null) {
				gos.finish();
				gos.close();
			}
		}
	}

	public static void compress(File inputFile, File outputFile)
			throws IOException {
		FileInputStream fis = null;
		FileOutputStream fos = null;

		try {
			fis = new FileInputStream(inputFile);
			fos = new FileOutputStream(outputFile, false);
			compress(fis, fos);
		} catch (IOException exception) {
			throw exception;
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
	}
}
